<script setup lang="ts">
  import { addPatientApi, editPatientApi, getPatientDetailApi } from '@/apis/patient'
  import type { PatientItem, PatientParams } from '@/types/patient'
  import { onMounted, ref } from 'vue'
  // 1. 定义表单数据
  const formData = ref({
    name: '',
    idCard: '',
    gender: 1,
    defaultFlag: 0,
  } as PatientParams)

  // 2.默认就诊人
  const defaultFlag = ref(false)
  const onSwitchChange = (res: UniHelper.SwitchOnChangeEvent) => {
    formData.value.defaultFlag = res.detail.value ? 1 : 0
  }

  // 3.校验规则
  const formRules = {
    name: {
      rules: [
        { required: true, errorMessage: '请填写患者姓名' },
        {
          pattern: '^[\u4e00-\u9fa5]{2,5}$',
          errorMessage: '患者姓名为2-5位中文',
        },
      ],
    },
    idCard: {
      rules: [
        { required: true, errorMessage: '请输入身份证号' },
        {
          pattern:
            '^[1-9]\\d{5}(?:18|19|20)\\d{2}(?:0[1-9]|10|11|12)(?:0[1-9]|[1-2]\\d|30|31)\\d{3}[\\dXx]$',
          errorMessage: '身份证号格式不正确',
        },
      ],
    },
    gender: {
      rules: [
        { required: true, errorMessage: '请选择性别' },
        {
          validateFunction(rule, value, data, callback) {
            // 1. 获取身份证号并截取倒数第二位
            const maleNum = formData.value.idCard.slice(16, 17)
            // 2. 判断性别
            // 3. 与提交的表单数据比较
            if (Number(maleNum) % 2 === value) {
              return true
            } else {
              callback('性别不匹配')
            }
          },
        },
      ],
    },
  }
  // 4.表单校验
  const form = ref()
  // 5.表单提交
  const onSubmit = async () => {
    try {
      await form.value.validate()
      // 校验成功
      if (props.id) {
        // 编辑用户
        await editPatientApi({
          idCard: formData.value.idCard,
          defaultFlag: formData.value.defaultFlag,
          id: props.id,
          name: formData.value.name,
          gender: formData.value.gender,
        } as PatientParams)
      } else {
        console.log(formData.value)
        // 添加用户
        await addPatientApi(formData.value)
      }

      // 提示用户
      uni.showToast({
        title: '成功',
      })
      // 返回上一页
      uni.navigateBack()
    } catch (error) {
      // 校验失败
      console.log(error)
    }
  }

  // 6. 获取id
  const props = defineProps<{
    id: string
  }>()
  const getDetail = async () => {
    if (props.id) {
      // 1. 获取用户详情
      const res = await getPatientDetailApi(props.id)
      // 2. 绑定数据
      formData.value = res

      // 3. 修改标题
      uni.setNavigationBarTitle({
        title: '编辑患者',
      })
      // 是否默认
      defaultFlag.value = res.defaultFlag === 1 ? true : false
      console.log(res.defaultFlag)
    }
  }
  getDetail()
</script>

<template>
  {{ formData }}
  <scroll-page>
    <view class="archive-page">
      <uni-forms border label-width="220rpx" ref="form" :model="formData" :rules="formRules">
        <uni-forms-item label="患者姓名" name="name">
          <uni-easyinput
            v-model="formData.name"
            placeholder-style="color: #C3C3C5; font-size: 32rpx"
            :styles="{ color: '#121826' }"
            :input-border="false"
            :clearable="false"
            placeholder="请填写真实姓名"
          />
        </uni-forms-item>
        <uni-forms-item label="患者身份证号" name="idCard">
          <uni-easyinput
            v-model="formData.idCard"
            placeholder-style="color: #C3C3C5; font-size: 32rpx"
            :styles="{ color: '#121826' }"
            :input-border="false"
            :clearable="false"
            placeholder="请填写身份证号"
          />
        </uni-forms-item>
        <uni-forms-item label="患者性别" name="gender">
          <uni-data-checkbox
            v-model="formData.gender"
            selectedColor="#16C2A3"
            :localdata="[
              { text: '男', value: 1 },
              { text: '女', value: 0 },
            ]"
          />
        </uni-forms-item>
        <uni-forms-item label="默认就诊人" name="defaultFlag">
          <view class="uni-switch">
            <switch
              @change="onSwitchChange"
              :checked="defaultFlag"
              color="#20c6b2"
              style="transform: scale(0.7)"
            />
          </view>
        </uni-forms-item>
        <button class="uni-button" @click="onSubmit">保存</button>
      </uni-forms>
    </view>
  </scroll-page>
</template>

<style lang="scss">
  @import './index.scss';
</style>
